<template>
  <div class="chat-page">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="flex items-center gap-4">
        <n-button
          text
          class="text-gray-600 hover:text-gray-900"
          @click="$router.back()"
        >
          <template #icon>
            <svg
              class="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M15 19l-7-7 7-7"
              ></path>
            </svg>
          </template>
          返回
        </n-button>

        <div v-if="currentCharacter" class="character-info">
          <div class="character-avatar">
            <div class="avatar-placeholder">
              {{ currentCharacter.name.charAt(0) }}
            </div>
          </div>
          <div>
            <h2 class="character-name">{{ currentCharacter.name }}</h2>
            <div class="character-traits">
              <n-tag
                v-for="trait in currentCharacter.personality.slice(0, 3)"
                :key="trait"
                size="small"
                type="info"
                class="mr-1"
              >
                {{ trait }}
              </n-tag>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-actions">
        <n-button @click="showConversationList = true"> 对话历史 </n-button>
        <n-button :loading="loading" @click="startNewConversation">
          新对话
        </n-button>
      </div>
    </div>

    <!-- 错误提示 -->
    <n-alert
      v-if="error"
      type="error"
      :title="error"
      closable
      class="mb-4"
      @close="clearError"
    />

    <!-- 聊天区域 -->
    <div class="chat-container">
      <!-- 消息列表 -->
      <div ref="messagesContainer" class="messages-container">
        <div v-if="messages.length === 0" class="empty-messages">
          <div class="text-center py-12">
            <svg
              class="w-16 h-16 text-gray-400 mx-auto mb-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-3.582 8-8 8a8.955 8.955 0 01-2.697-.413l-2.725.725.725-2.725A8.955 8.955 0 013 12c0-4.418 3.582-8 8-8s8 3.582 8 8z"
              ></path>
            </svg>
            <h3 class="text-lg font-medium text-gray-900 mb-2">开始对话</h3>
            <p class="text-gray-500">
              向{{ currentCharacter?.name }}说点什么吧！
            </p>
          </div>
        </div>

        <div v-else class="messages-list">
          <div
            v-for="message in messages"
            :key="message.id"
            :class="[
              'message',
              message.role === 'user' ? 'user-message' : 'assistant-message',
            ]"
          >
            <div class="message-avatar">
              <div v-if="message.role === 'user'" class="user-avatar">
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    fill-rule="evenodd"
                    d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
                    clip-rule="evenodd"
                  ></path>
                </svg>
              </div>
              <div v-else class="character-avatar-small">
                {{ currentCharacter?.name.charAt(0) }}
              </div>
            </div>

            <div class="message-content">
              <div class="message-bubble">
                <p class="message-text">{{ message.content }}</p>
              </div>
              <div class="message-time">
                {{ formatTime(message.createdAt) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 正在输入指示器 -->
        <div v-if="isTyping" class="typing-indicator">
          <div class="message assistant-message">
            <div class="message-avatar">
              <div class="character-avatar-small">
                {{ currentCharacter?.name.charAt(0) }}
              </div>
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div class="typing-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-container">
          <n-input
            v-model:value="inputMessage"
            type="textarea"
            placeholder="输入消息..."
            :rows="3"
            :maxlength="1000"
            :disabled="loading"
            class="message-input"
            @keydown.enter.exact.prevent="sendMessage"
            @keydown.enter.shift.exact="() => {}"
          />
          <div class="input-actions">
            <n-button
              type="primary"
              :loading="loading"
              :disabled="!inputMessage.trim()"
              @click="sendMessage"
            >
              发送
            </n-button>
          </div>
        </div>
        <div class="input-hint">
          <span class="text-sm text-gray-500"
            >按 Enter 发送，Shift + Enter 换行</span
          >
        </div>
      </div>
    </div>

    <!-- 对话历史抽屉 -->
    <n-drawer
      v-model:show="showConversationList"
      :width="400"
      placement="right"
    >
      <n-drawer-content title="对话历史">
        <div class="conversation-list">
          <div
            v-for="conversation in currentCharacterConversations"
            :key="conversation.id"
            :class="[
              'conversation-item',
              { active: conversation.id === currentConversation?.id },
            ]"
            @click="switchConversation(conversation)"
          >
            <div class="conversation-title">
              {{ conversation.title || '未命名对话' }}
            </div>
            <div class="conversation-time">
              {{ formatTime(conversation.updatedAt) }}
            </div>
          </div>

          <div
            v-if="currentCharacterConversations.length === 0"
            class="empty-conversations"
          >
            <p class="text-gray-500 text-center py-8">暂无对话历史</p>
          </div>
        </div>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  NButton,
  NAlert,
  NTag,
  NInput,
  NDrawer,
  NDrawerContent,
  useMessage,
} from 'naive-ui';
import { useRoleplayStore } from '@/stores/roleplay';
import type { Conversation } from '@/types/roleplay';

const router = useRouter();
const route = useRoute();
const message = useMessage();
const store = useRoleplayStore();

// Props
const props = defineProps<{
  characterId: string;
  conversationId?: string;
}>();

// 从store中获取状态和方法
const {
  currentCharacter,
  currentConversation,
  currentCharacterConversations,
  messages,
  loading,
  error,
  selectCharacter,
  selectConversation,
  createConversation,
  sendMessage: storeSendMessage,
  clearError,
} = store;

// 本地状态
const inputMessage = ref('');
const isTyping = ref(false);
const showConversationList = ref(false);
const messagesContainer = ref<HTMLElement>();

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return;

  const messageContent = inputMessage.value.trim();
  inputMessage.value = '';

  try {
    isTyping.value = true;
    await storeSendMessage(messageContent);

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('发送消息失败:', error);
  } finally {
    isTyping.value = false;
  }
};

// 开始新对话
const startNewConversation = async () => {
  if (!currentCharacter.value) return;

  try {
    const conversation = await createConversation(currentCharacter.value.id);
    router.push({
      name: 'Chat',
      params: {
        characterId: currentCharacter.value.id,
        conversationId: conversation.id,
      },
    });
  } catch (error) {
    console.error('创建对话失败:', error);
  }
};

// 切换对话
const switchConversation = async (conversation: Conversation) => {
  showConversationList.value = false;
  router.push({
    name: 'Chat',
    params: {
      characterId: props.characterId,
      conversationId: conversation.id,
    },
  });
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 格式化时间
const formatTime = (dateString: string) => {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  if (diff < 60000) {
    // 1分钟内
    return '刚刚';
  } else if (diff < 3600000) {
    // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`;
  } else if (diff < 86400000) {
    // 1天内
    return `${Math.floor(diff / 3600000)}小时前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 初始化页面
const initializePage = async () => {
  try {
    // 加载角色信息
    if (
      !currentCharacter.value ||
      currentCharacter.value.id !== props.characterId
    ) {
      // 这里需要根据ID加载角色，暂时跳转回列表页
      router.push({ name: 'CharacterList' });
      return;
    }

    // 如果有对话ID，加载对话
    if (props.conversationId) {
      const conversation = currentCharacterConversations.value.find(
        (conv) => conv.id === props.conversationId
      );
      if (conversation) {
        await selectConversation(conversation);
      }
    }

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('初始化页面失败:', error);
  }
};

// 监听消息变化，自动滚动到底部
watch(
  messages,
  () => {
    nextTick(() => {
      scrollToBottom();
    });
  },
  { deep: true }
);

// 监听路由参数变化
watch(
  () => [props.characterId, props.conversationId],
  () => {
    initializePage();
  },
  { immediate: true }
);

onMounted(() => {
  initializePage();
});
</script>

<style scoped>
@reference "@/styles/app.css";

.chat-page {
  @apply h-screen flex flex-col bg-gray-50;
}

.chat-header {
  @apply bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between;
}

.character-info {
  @apply flex items-center gap-3;
}

.character-avatar {
  @apply flex-shrink-0;
}

.avatar-placeholder {
  @apply w-10 h-10 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold;
}

.character-name {
  @apply text-lg font-semibold text-gray-900;
}

.character-traits {
  @apply flex gap-1 mt-1;
}

.chat-actions {
  @apply flex gap-2;
}

.chat-container {
  @apply flex-1 flex flex-col min-h-0;
}

.messages-container {
  @apply flex-1 overflow-y-auto px-6 py-4;
}

.messages-list {
  @apply space-y-4;
}

.message {
  @apply flex gap-3;
}

.user-message {
  @apply flex-row-reverse;
}

.message-avatar {
  @apply flex-shrink-0;
}

.user-avatar {
  @apply w-8 h-8 bg-gray-500 text-white rounded-full flex items-center justify-center;
}

.character-avatar-small {
  @apply w-8 h-8 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-bold;
}

.message-content {
  @apply max-w-xs sm:max-w-md lg:max-w-lg;
}

.user-message .message-content {
  @apply text-right;
}

.message-bubble {
  @apply px-4 py-2 rounded-lg;
}

.user-message .message-bubble {
  @apply bg-blue-500 text-white;
}

.assistant-message .message-bubble {
  @apply bg-white border border-gray-200 text-gray-900;
}

.message-text {
  @apply whitespace-pre-wrap;
}

.message-time {
  @apply text-xs text-gray-500 mt-1;
}

.typing-indicator {
  @apply mt-4;
}

.typing-dots {
  @apply flex gap-1;
}

.typing-dots span {
  @apply w-2 h-2 bg-gray-400 rounded-full animate-pulse;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

.input-area {
  @apply bg-white border-t border-gray-200 p-4;
}

.input-container {
  @apply flex gap-3 items-end;
}

.message-input {
  @apply flex-1;
}

.input-hint {
  @apply mt-2 text-center;
}

.conversation-list {
  @apply space-y-2;
}

.conversation-item {
  @apply p-3 rounded-lg cursor-pointer hover:bg-gray-100 transition-colors;
}

.conversation-item.active {
  @apply bg-blue-50 border border-blue-200;
}

.conversation-title {
  @apply font-medium text-gray-900;
}

.conversation-time {
  @apply text-sm text-gray-500 mt-1;
}

.empty-messages {
  @apply bg-white rounded-lg shadow-sm border border-gray-200;
}

.empty-conversations {
  @apply text-center py-8;
}
</style>
